const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const url = 'mongodb://huirui:zhangli1992@ds012178.mlab.com:12178/node_express';
const Bear = require('./models/bear');

mongoose.connect(url);
mongoose.set('debug', true)
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

const port = process.env.PORT || 8088;

//API router setting

const router = express.Router();

router.use((req, res, next) => {
    console.log('Something is happening.')
    next();
})

router.get('/', (req, res)=>{
    res.json({message: 'Hooray! Welcome to our API!'})
})

router.route('/bears')
    .post((req, res) => {
        let bear = new Bear();
        bear.params = req.body;

        bear.save((err) => {
            if(err)
                res.send(err);
            res.json({message: 'Bear created!'});
        })
    })
    .get((req, res) => {
        Bear.find((err, bears) => {
            if(err)
                res.send(err);
            res.json(bears);
        })
    })

router.route('/bears/:bear_id')
    .get((req, res) => {
        Bear.findById(req.params.bear_id, (err, bear) => {
            if(err)
                res.send(err);
            res.json(bear);
        })
    })
    .put((req, res) => {
        Bear.findById(req.params.bear_id, (err, bear) => {
            if(err)
                res.send(err)
            bear.name = req.body.name;
            bear.save((err) => {
                if(err)
                    res.send(err);
                res.json({message: 'Bear updated!'})
            })
        })
    })
    .delete((req, res) => {
        Bear.remove({
            _id: req.params.bear_id
        },(err, bear) => {
            if(err)
                res.send(err)
            res.json({message: 'Successfully deleted!'})
        })
    })
app.use('/api', router);

app.listen(port);

console.log('Sever started on port ' + port);